package com.dongdongshop.jop;

import com.dongdongshop.emil.EmailModel;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.util.MailUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import java.util.Date;
import java.util.Properties;

@DisallowConcurrentExecution//禁止并发
public class OrderJob extends QuartzJobBean {
    @DubboReference
    private OrderService orderService;
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        try {
            /*查询昨日订单数量和今日订单数量
             *  (今日-昨日) / 昨日 * 100%
             * */
            double orderYester = orderService.selectByYesterday();
            double orderToDay = orderService.selectByToday();
            double d = (orderToDay - orderYester)/orderYester * 100;
            String str = "昨日订单量 "+orderYester+" 今日订单量  "+orderToDay+" 环比增加 "+Math.floor(d)+"% ";
            System.out.println(new Date() + str);
            textMail(str);
        }catch (Exception e){
            System.out.println("统计订单异常");
            e.printStackTrace();
        }
    }
    public void textMail(String content) throws Exception {
        EmailModel emailModel = new EmailModel();
        emailModel.setRecipientAddress("13453480269@163.com");

        //1、连接邮件服务器的参数配置
        Properties props = new Properties();
        //  设置用户的认证方式
        props.setProperty("mail.smtp.auth", "true");
        //  设置传输协议
        props.setProperty("mail.transport.protocol", "smtp");
        //  设置发件人的SMTP服务器地址                ↓
        props.setProperty("mail.smtp.host", "smtp.qq.com");
        //2、创建定义整个应用程序所需的环境信息的 Session 对象
        Session session = Session.getInstance(props);
        //  设置调试信息在控制台打印出来
        session.setDebug(true);
        //3、创建邮件的实例对象
        Message msg = MailUtil.getTextMessage(session, emailModel,content);
        //4、根据session对象获取邮件传输对象Transport
        Transport transport = session.getTransport();
        //  设置发件人的账户名和授权码
        transport.connect(emailModel.getSenderAccount(), emailModel.getSenderPassword());
        //  发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(msg, msg.getAllRecipients());


        //5、关闭邮件连接
        transport.close();
    }
}
